﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Helper_Ji
{
    public static class Helper_Cmd
    { 
     
        /// <summary>
        /// 执行Netstat查找PID
        /// </summary>
        public static string netstat = "netstat -ano|findstr ";
     
        /// <summary>
        /// 关闭PID
        /// </summary>
        public static string killPID = "tskill ";

        /// <summary>
        /// 执行CMD命令
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public static string StartCmd(string cmd)
        {
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
            process.StandardInput.WriteLine(cmd);
            process.StandardInput.WriteLine("exit");
            string output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            return output;
        }

        /// <summary>
        /// 获取PID
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public static string GetPid(string cmd,int port)
        {
            var list = cmd.Split(new string[] { " ", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
           int outNum=0;
           bool start = false;
            foreach(var portNum in list)
           {
               if (portNum == "-ano|findstr")
               {
                   start = true;
               }
               if (start&&int.TryParse(portNum, out outNum))
               {
                   if (outNum != port)
                   {
                       return outNum.ToString ();
                   }
               }
           }
            return string.Empty;
        }
    }
}
